/*global Ext, Application */
 
Ext.BLANK_IMAGE_URL = './ext/resources/images/default/s.gif';

// application main entry point
Ext.onReady(function() {
 
    Ext.QuickTips.init();	
	initData();
	
	// create the data store
    //ratingsGrid = new RatingsGrid();
	ratingsGrid = buildGrid(myData);
	ratingsGrid.region = 'center';
	
	var taskActions = new Ext.Panel({
    	frame:true,
    	title: 'Actions',
    	collapsible:true,
    	contentEl:'task-actions',
    	titleCollapse: true
    });
	
	var actionPanel = new Ext.Panel({
    	id:'action-panel',
    	region:'west',
    	split:true,
    	collapsible: true,
    	collapseMode: 'mini',
    	width:200,
    	minWidth: 150,
    	border: false,
    	baseCls:'x-plain',
    	items: [taskActions]
    });		
	
	viewport = new Ext.Viewport({
           layout:'border',
           items:[actionPanel, ratingsGrid]});
    // code here
	var ab = actionPanel.body;
    ab.on('mousedown', doAction, null, {delegate:'a'});
	ab.on('click', Ext.emptyFn, null, {delegate:'a', preventDefault:true});
	
 
}); // eo function onReady

var db;
var myData = [];


// Open this page's local database.
function initData() {
  var success = false;

  if (window.google && google.gears) {
    try {
      db = google.gears.factory.create('beta.database');

      if (db) {
        db.open('raitings-v1');
		//db.execute('insert into users values (?, ?)', ['Helper', 23]);
        db.execute('create table if not exists users' +
           ' (name text, rating int)');
        success = true;
        // Initialize the UI at startup.
        displayUsers();
      }

    } catch (ex) {
      //setError('Could not create database: ' + ex.message);
    }
  }
}

var actions = {
	'action-new' : function() {
		Ext.Msg.prompt('Add new player', 'Please enter player name:', 
			function(btn, text){
			    if (btn == 'ok'){
			        db.execute('insert into users values (?, ?)', [text, 0]);
					ratingsGrid.getStore().loadData([[text, 0]], true);					
			    }
			}
		);
	}
}

function doAction(e, t){
	e.stopEvent();
	actions[t.id]();
}

function displayUsers() {
  // Get the 3 most recent entries. Delete any others.
  //db.execute('insert into users values (?, ?)', ['Gazer', 765]);
  var rs = db.execute('select * from users order by rating desc');
  var index = 0;
  
  while (rs.isValidRow()) {
	var myArr = [rs.field(0), rs.field(1)];
	myData[myData.length] = myArr;
    ++index;
    rs.next();
  }
  rs.close();  
}
